﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SAP.BusinessOne.ActiveDirectory.Web
{
    /// <summary>
    /// Handle request like /handler?{alias}
    /// </summary>
    public class QueryHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var request = context.Request;
            var response = context.Response;

            // common header
            response.ContentType = "application/json";

            var alias = request.Url.Query;
            if (string.IsNullOrWhiteSpace(alias))
            {
                PrintError(response, 400, new ArgumentNullException("alias"));
                return;
            }

            try
            {
                var identity = new ActiveDirectoryUser(HttpUtility.UrlDecode(alias.Substring(1)));
                response.Write(identity.ToString());
            }
            catch (Exception e)
            {
                PrintError(response, 500, e);
            }
        }

        private void PrintError(HttpResponse response, int status, Exception e)
        {
            response.StatusCode = status;
            response.Write(e.ToJson());
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}